<?php

namespace addons\recharge\model;

use addons\litestore\controller\api\Wxapp;
use app\admin\model\OrderSfLog;
use app\common\model\User;
use Exception;
use think\Db;
use think\Model;

/**
 * 充值订单模型
 */
class Order extends Model
{

    // 表名
    protected $name = 'recharge_order';
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = '';
    // 追加属性
    protected $append = [];


    public function order_add($user_id,$money,$type = 1,$vip_id = null)
    {

        Db::startTrans();
        // 记录订单信息
        $this->save([
            'order_no'   => $this->orderNo(),
            'vip_id'   => $vip_id,
            'user_id'   => $user_id,
            'amount'    => $money,
            'type'    => $type,
            'payamount' => 0,
            'paytype'   => 'Wxapp',
            'status'    => 'created'
        ]);
       
        Db::commit();
        return true;
    }

    protected function orderNo()
    {
        return date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }


    public function payDetail($order_no)
    {
        return self::get(['order_no' => $order_no, 'status' => 'created']);
    }


    public function updatePayStatus($transaction_id,$payamount)
    {
        Db::startTrans();

        // 更新订单状态
        $this->save([
            'pay_time' => time(),
            'status' => 'paid',
            'payamount' => $payamount / 100,
            'transaction_id' => $transaction_id,
        ]);
        
        $vip = db('vip')->where('id',$this->data['vip_id'])->find();
        $user = db('user')->where('id',$this->data['user_id'])->find();
        $user = User::get($this->data['user_id']);
        
        $vip_log_model = new \app\admin\model\VipLog;
        $type_name = db('category')->field('id,name')->where('id',$vip['type'])->value('name');
        $vip_log = $vip;
        unset($vip_log['id']);
        $vip_log['user_id'] = $user->id;
        $vip_log['nickname'] = $user->nickname;
        $vip_log['type_name'] = $type_name;
        $vip_log['used_service_number'] = $vip['service_number'];
        $vip_log['end_time'] = strtotime('+1 year');
        $vip_log_model->allowField(true)->save($vip_log);
        
        $user->level_time = strtotime('+1 year');
        $user->level  = 1;
        $user->save();
        Db::commit();
        return true;
    }

    

}
